package com.felix.tests;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.felix.tests.dto.DeviceMap;
import com.felix.tests.dto.PiXiuMqttDTO;
import com.felix.tests.util.ConfigurationTools;
import felix.things.router.modbus.mapping.TypeTagMapping;
import felix.things.router.modbus.response.ModBusDataProcessor;
import felix.things.router.mqtt.MqttUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Felix
 * @date 2019/10/31
 **/
@Component
public class LightDataProcess implements ModBusDataProcessor {
    @Autowired
    private MqttUtils mqttUtils;

    private ObjectMapper mapper = new ObjectMapper();

    private List<TypeTagMapping> tagMappings;

    @Override
    public List<TypeTagMapping> getMappings() {
        if (tagMappings == null) {
            DeviceMap deviceMap;
            DeviceMap keyDic;
            try {
                deviceMap = ConfigurationTools.readFileConfiguration("DeviceMap.json", DeviceMap.class);
                keyDic = ConfigurationTools.readFileConfiguration("KeyDic.json", DeviceMap.class);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            Map<String, String> keymap = keyDic.getKeyDic();
            DeviceMap.Devices lighting = deviceMap.getDevices().stream().filter(devices -> devices.getId() == 201).findFirst().get();
            tagMappings = lighting.getDevices().stream().map(deviceItem -> {
                String parameterName = deviceItem.getParameterName();
                String enKey = keymap.get(parameterName);
                return new TypeTagMapping(deviceItem.getGlobalId() + "_" + enKey, deviceItem.getRegister());
            }).collect(Collectors.toCollection(ArrayList::new));
        }
        return tagMappings;
    }

    @Override
    public void processorData(String tag, HashMap<String, Object> response, int start, int end) {
        String preName = "Test_Lighting_";
        HashMap<String, Map<String, Long>> sendMsg = new HashMap<>();
        // TODO 拆分key和tag，组合推送数据
        ArrayList<PiXiuMqttDTO> msgList = new ArrayList<>();
        response.forEach((s, o) -> {
            String[] split = s.split("_");
            String DeviceID = preName + split[0];
            String key = split[1];
            Long val = (Long) o;
            sendMsg.putIfAbsent(DeviceID, new HashMap<>(3));
            Map<String, Long> map = sendMsg.get(DeviceID);
            map.put(key, val);
        });
        sendMsg.forEach((s, stringLongMap) -> {
            PiXiuMqttDTO item = new PiXiuMqttDTO();
            item.setDeviceId(s);
            item.setDeviceType("Lighting");
            item.setTimeseriesJsonData(stringLongMap);
            msgList.add(item);
        });
        try {
            String msg = mapper.writeValueAsString(msgList);
            mqttUtils.publishMsg("sensors", msg);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getTag() {
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return "tcp:LightingSystemSlave";
    }
}
